# -*- coding: utf-8 -*-
import sys
from os import chdir
from os.path import dirname, realpath

levinDir = dirname(dirname(realpath(sys.argv[0])))
chdir(levinDir)
print levinDir
sys.path.append( levinDir )
import levin.levinCommon as levinCommon
import gettext
gettext.install('LeVin', levinCommon.LEVIN_PO, unicode=True)


import levin.world.wineObjects as wineObjects

#import levin.wineAreas as wineAreas
import levin.world.wineObjects as wineObjects
import levin.wineSelector as wineSelector
from levin.world.worldArea import WorldArea

from operator import attrgetter


#hs = """u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">\n<html><head><meta name="qrichtext" content="1" /><style type="text/css">\np, li { white-space: pre-wrap; }\n</style></head><body style=" font-family:\'Sans\'; font-size:10pt; font-weight:400; font-style:normal;">\n<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">"""

#DEFAULT_user = 'user_sync_test1.pk
#DEFAULT_user = 'user_sync_test0.pk'
DEFAULT_user = 'user4.pk'
#DEFAULT_user = 'none'
#DEFAULT_user = '/home/delsart/.config/LeVin/user.pk'

import levin.world.areaUtils as areaUtils
#areaUtils.loadAll(DEFAULT_user, worldc= "world_nospain.pk")
areaUtils.loadAll(DEFAULT_user, worldc= "newworld.pk")
#areaUtils.loadAll("user4.pk", worldc= "data/world.pk")

execfile('tests/noguiUpdateWorldTest.py')


    

def loadAlternate(name):
    w = wineAreas.WorldArea("World")
    w.loadContent('world2.pk', user=False)
    w.loadContent(name,user=True)

    return w

#loadFromDir = wineAreas.loadFromDir    

def loadW1():
    global w1
    w1 = loadAlternate('user_sync_test1.pk')
    
def saveDefault():
    wineAreas.wineWorld.saveUserContent(DEFAULT_user)

    
#wineAreas.loadAll()
#wineAreas.levinCommon.wineWorld = wineAreas.WorldArea("World")
wineWorld = levinCommon.wineWorld



def testUpdateDataSystem(loctest=False):
    wineWorld.France['bla0']
    mm=wineWorld.France['bla0']['mmmm']
    mm.addCepages(0,'SDAS d', True)
    print ' user area ', wineWorld.France._user_subAreas.keys()
    print ' sub sub user cepages ' , mm._user_cepages
    if loctest:
        wineWorld.France.addSubArea('BLA1', addUserArea=False, localname='bla0')
    else:
        a=wineWorld.France.addSubArea('bla0', addUserArea=False)
        #a.localname = 'bla0'
    print ' systeme area ', wineWorld.France._system_subAreas.keys()
    print 

    wineWorld.France._updateUDataFromSData()
    print ' user area ', wineWorld.France._user_subAreas.keys()
    print ' systeme area ', wineWorld.France._system_subAreas.keys()
    print ' sub sub user ', wineWorld.France['bla0']._user_subAreas.keys()
    print ' sub sub user cepages ', wineWorld.France['bla0']['mmmm']._user_cepages
    

def htmlparse():
    from HTMLParser import HTMLParser

    class MyHTMLParser(HTMLParser):
        _intag = None
        content = []
        def handle_starttag(self, tag, attrs):
            self._intag = tag
            #print "Encountered a start tag:", tag
        ## def handle_endtag(self, tag):
        ##     print "Encountered  an end tag:", tag
        def handle_data(self, data):
            #print "Encountered   some data in tag :", self._intag
            #print "Encountered   some data:", data

            if self._intag=="p" and data != '\n':
                print 'saving ||%s||'%( data,)
                self.content.append(data)

    parser = MyHTMLParser()

    for b in wineWorld.getWines():
        print '********************************************'
        parser.content=[]
        parser.feed(b.otherInfo)
        print parser.content
        b.otherInfo = u'\n'.join(parser.content)

def filltastings():
    execfile('tmptasting.py')

    print 'AAAAAAAAAAAAAAAAA'
    france = wineWorld['France']

    regionTR= dict( (v,u) for u,v in zip([u'Burgundy', u'Bordeaux', u'Alsace', u'Rhone Valley', u'Beaujolais', u'South West', u'Champagne', u'Jura', u'Savoy', u'Provence', u'Languedoc-Roussillon', u'Corsica', u'Piemont', u'Tuscany'],
                                         [u'Bourgogne', u'Bordeaux', u'Alsace', u'Vall\xe9e du Rh\xf4ne', u'Beaujolais', u'Sud-Ouest', u'Champagne', u'Jura', u'Savoie', u'Provence', u'Languedoc-Roussillon', u'Corse', u'Pi\xe9mont', u'Toscane']) )

    import wineObjects
    for  b in tt :
        r, a , c = b[0]
        tlist = b[1]
        #print r, a, c
        r = regionTR[ r ]
        region = france[r]
        appellationA = region.getSubAreaRec(a, fuzzy=True)
        if appellationA is None:
            print ' NO APPELLATION ',a
        bott = appellationA.getWine(c)
        print r, '++++', a, '_', appellationA, '  *** ', c , bott
        print '   ',tlist[0]
        bott.tastings = []
        for t in tlist:
            newt = wineObjects.Tasting()
            newt.fromDict(t.items())
            bott.tastings.append(newt)
    
    #app = region[a]    
    #print region ,app

def fixColor():
    for w in wineWorld.getWines():
        if w.color is None:
            w.color = 0

def fixMillesime():
    for w in wineWorld.getWines():
        w.millesime = int(w.millesime)
def fixBottleID():
    for w in wineWorld.getWines():
        w.bottleId= wineAreas.uuidID()
        #w.bottleId= wineAreas.timeId()

def fixTastings():
    for w in wineWorld.getWines():
        if w.tastings is None:
            continue
        for t in w.tastings:
            t.bottle = w
def fixTastingsID():
    for w in wineWorld.getWines():
        if w.tastings is None:
            continue
        for t in w.tastings:
            t.tastingId = w._tastingId()

def voidUserCepages():
    for a in wineWorld.iter_subAreas(reccursive=True):
        print 'voiding ', a.name
        a._user_cepages = [ [] , [],[] ]
    

def fixColor():
    def extL( l , N):
        l.extend( [ [] ]* (N-len(l))  )
    N = len(wineObjects.colors)
    for a in wineWorld.iter_subAreas():
        if a._user_cepages :
            extL(a._user_cepages,N)

import datetime
now=datetime.datetime.now()
def fixUpdate():
    for w in wineWorld.getWines():
        w.lastUpdate = now

def fixDates():
    from datetime import date
    for w in  wineWorld.iterWines():
        dat = w.acquireDate
        print ' w ',w.cru_name, w, dat
        if dat:
            if '-' in dat:
                d, m, y = (int(s) for s in dat.split('-') )
            else:
                d, m, y = (int(s) for s in dat.split('/') )
                if y < 30: y +=2000
            w.acquireDate = date(y,m,d).toordinal()
            
def fixDatesTastings():
    from datetime import date
    for w in  wineWorld.iterTastings():
        dat = w.date
        if dat:
            if '-' in dat:
                d, m, y = (int(s) for s in dat.split('-') )
            else:
                d, m, y = (int(s) for s in dat.split('/') )
                if y < 30: y +=2000
                
            w.date = date(y,m,d).toordinal()
        
    

def modifBottle( b, s=' Mod0' ):
    b.cru_name = b.cru_name+s
    b.acquireComment = b.acquireComment +s
    b.lastUpdate = now

def modifTasting(b , s=''):
    t = b.tastings[0]
    t.comment = t.comment +s
    b.lastUpdate = now
    
def modifTastingRemove(b,s='' ):
    b.removeTasting(b.tastings[-1])    
    b.lastUpdate = now
    
def modifTastingAdd(b ,s=''):
    t = wineObjects.Tasting()
    t.date = '29/01/01'
    t.rate =4
    t.comment = 'dss s '+s
    b.tastings.append(t)
    b.lastUpdate = now


def printUserCepages(area):
    if area._user_cepages :
        print area.name  ,'  ', area._user_cepages 

def voidUserCepages(area):
    if area._user_cepages :
        area._user_cepages = None
        
    

def applyToAllAreas(area, func):
    """ usage example : applyToAllAreas(levinCommon.wineWorld, printUserCepages)  """
    for a in area.iter_subAreas(True):
        func(a)
    func(area)


def testSync(w, ind, modStr='', tastingMod = []):
    l = w.getWines()
    for i in ind:
        modifBottle( l[i] , modStr)
    # tasting modifs
    for i,f in zip(tastingMod, [modifTasting, modifTastingAdd, modifTastingRemove]):
        f(l[i],modStr)
        
    #saveDefault()

    from  shutil import copy

class SynchroTest(object):

    def __init__(self,resolveF = None, d0 = 'testData/test0/', d1 = 'testData/test1/' , w0IsWorldW=False):
        if resolveF:
            wineAreas.WorldArea.resolveConflict = resolveF
        self.now=datetime.datetime.now()
        self.sec1 = datetime.timedelta(seconds=1)
        self.dir0 = d0
        self.dir1 = d1
        self.w0IsWorldW = w0IsWorldW
        
    def setup(self):
        from  shutil import copy        
        copy('user3.pk',self.dir0+'/user.pk')
        w0 = loadFromDir(self.dir0)
        if self.w0IsWorldW:
            wineAreas.wineWorld = w0
        w0.worldId = 'W0'
        testSync(w0, [0,1,2] , 'mod 0', tastingMod=[0,0])
        nb = wineAreas.Bottle(country="France",region="Bordeaux" , appellation=u"Haut-Médoc" , cru_name="TDSAD ds",millesime=2010)
        w0.addWine(nb)

        self.w0 = w0

        copy('user3.pk',self.dir1+'/user.pk')
        w1 = loadFromDir(self.dir1)
        w1.worldId = 'W1'
        testSync(w1, [0,1,3] , 'mod 1')
        nb = wineAreas.Bottle(country="France",region="Bordeaux" , appellation=u"Margaux" , cru_name="pppppeeepr",millesime=2010)
        w1.addWine(nb)

        self.w1 = w1

        self.unsync()
        
    def unsync(self):

        now , sec1 = self.now, self.sec1
        self.w1.synchroDict['W0'] = now - sec1

        self.w0.synchroDict['W1'] = now - sec1



    def sync(self,*l):
        # ------ 
        self.w0.synchronize(self.w1)
        #  -----

    def save(self):
        self.w0.saveUserContent('user_sync_test0.pk')
        self.w1.saveUserContent('user_sync_test1.pk')

    def fullSyncTest(self, *l):
        self.setup()
        self.sync()
        #self.save()
        
def fullSyncTest(*l):
    sec1 = datetime.timedelta(seconds=1)

    from  shutil import copy
    copy('user3.pk','user_sync_test0.pk')
    w0 = loadAlternate('user_sync_test0.pk')
    w0.worldId = 'W0'
    testSync(w0, [0,1,2] , 'mod 0', tastingMod=[0,0])
    nb = wineAreas.Bottle(country="France",region="Bordeaux" , appellation=u"Haut-Médoc" , cru_name="TDSAD ds",millesime=2010)
    w0.addWine(nb)
    
    w0.synchroDict['W1'] = now - sec1


    copy('user3.pk','user_sync_test1.pk')
    w1 = loadAlternate('user_sync_test1.pk')
    w1.worldId = 'W1'
    testSync(w1, [0,1,3] , 'mod 1')
    nb = wineAreas.Bottle(country="France",region="Bordeaux" , appellation=u"Margaux" , cru_name="pppppeeepr",millesime=2010)
    w1.addWine(nb)
    w1.synchroDict['W0'] = now - sec1

    ## ------ 
    w0.synchronize(w1)
    ##  -----

    w0.saveUserContent('user_sync_test0.pk')
    w1.saveUserContent('user_sync_test1.pk')
    return 

def checkTest():
    w0 = loadAlternate('user_sync_test0.pk')
    w1 = loadAlternate('user_sync_test1.pk')
    return w0.compare(w1)

    #w0.saveUserContent(DEFAULT_user)

    

    
    
def callForWines(f, w=wineWorld):    
    return [f(b) for b in w.getWines() ]
w0 = wineWorld
w1 = None
